<template>
  <header class="header">
    <div class="nav-container">
      <div class="logo" @click="goHome">
        <div class="logo-icon">福</div>
        <div class="logo-text">企业福利商城</div>
      </div>

      <ul class="main-nav">
        <li
          v-for="item in navItems"
          :key="item.path"
          :class="['nav-item', { active: isActive(item.path) }]"
          @click="navigateTo(item.path)"
        >
          {{ item.name }}
        </li>
      </ul>

      <div class="user-info">
        <div class="balance" v-if="userStore.userInfo">
          <span class="balance-icon">¥</span>
          <span>{{ formatBalance(userStore.userInfo.accountBalance) }}</span>
        </div>
        <el-dropdown @command="handleCommand">
          <el-avatar 
            :key="avatarKey"
            :size="36" 
            :src="getAvatarUrl" 
            class="avatar"
          >
            <template #default>{{ userInitial }}</template>
          </el-avatar>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="card-exchange">福利卡兑换</el-dropdown-item>
              <el-dropdown-item command="orders">我的订单</el-dropdown-item>
              <el-dropdown-item command="favorites">我的收藏</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </header>
</template>

<script setup>
import { computed, ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 头像刷新key
const avatarKey = ref(0)

// 导航菜单项
const navItems = [
  { name: '首页', path: '/home' },
  { name: '商品分类', path: '/categories' },
  { name: '福利卡兑换', path: '/card-exchange' },
  { name: '购物车', path: '/cart' },
  { name: '个人中心', path: '/profile' }
]

// 判断当前路由是否激活
const isActive = (path) => {
  if (path === '/home' && route.path === '/home') return true
  return route.path.startsWith(path)
}

// 获取头像URL
const getAvatarUrl = computed(() => {
  const avatar = userStore.userInfo?.avatar
  if (!avatar) return null
  // 如果是完整URL，直接返回
  if (avatar.startsWith('http')) return avatar
  // 如果是相对路径，拼接基础URL
  return `http://localhost:8092/api${avatar}`
})


// 获取用户首字母
const userInitial = computed(() => {
  return userStore.userInfo?.realName?.charAt(0) || '用'
})

// 监听userInfo变化，更新头像key以强制刷新
watch(() => userStore.userInfo?.avatar, () => {
  avatarKey.value++
})

// 格式化余额显示（后端为元，保留两位小数）
const formatBalance = (balance) => {
  if (balance == null) return '0.00'
  const num = typeof balance === 'number' ? balance : parseFloat(balance)
  if (Number.isNaN(num)) return '0.00'
  return num.toFixed(2)
}

// 导航到指定路径
const navigateTo = (path) => {
  if (route.path !== path) {
    router.push(path)
  }
}

// 返回首页
const goHome = () => {
  router.push('/home')
}

// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'card-exchange':
      router.push('/card-exchange')
      break
    case 'orders':
      router.push('/order/list')
      break
    case 'favorites':
      router.push('/favorites')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await userStore.logout()
    ElMessage.success('已退出登录')
    // 跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
    ElMessage.error('退出登录失败')
    // 即使出错也跳转到登录页
    router.push('/login')
  }
}

// 挂载时刷新用户信息，确保余额为最新
onMounted(() => {
  if (userStore.token) {
    userStore.refreshUserInfo()
  }
})
</script>

<style lang="scss" scoped>
.header {
  background-color: white;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 1000;
}

.nav-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  max-width: 1200px;
  margin: 0 auto;
}

.logo {
  display: flex;
  align-items: center;
  cursor: pointer;

  .logo-icon {
    width: 36px;
    height: 36px;
    background: linear-gradient(135deg, #409EFF 0%, #64b5ff 100%);
    border-radius: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 10px;
    color: white;
    font-weight: bold;
    font-size: 18px;
  }

  .logo-text {
    font-size: 20px;
    font-weight: 600;
    color: #409EFF;
  }
}

.main-nav {
  display: flex;
  list-style: none;
  height: 100%;
  margin: 0;
  padding: 0;
}

.nav-item {
  padding: 0 20px;
  height: 100%;
  display: flex;
  align-items: center;
  cursor: pointer;
  position: relative;
  font-weight: 500;
  transition: color 0.3s;

  &:hover {
    color: #409EFF;
  }

  &.active {
    color: #409EFF;
  }

  &.active::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 3px;
    background-color: #409EFF;
  }
}

.user-info {
  display: flex;
  align-items: center;
}

.balance {
  margin-right: 20px;
  display: flex;
  align-items: center;
  background-color: #f0f9ff;
  padding: 6px 12px;
  border-radius: 16px;
  color: #409EFF;
  font-weight: 500;

  .balance-icon {
    margin-right: 5px;
  }
}

.avatar {
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    opacity: 0.8;
    transform: scale(1.05);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .nav-container {
    padding: 0 12px;
  }

  .main-nav {
    display: none;
  }

  .balance {
    display: none;
  }

  .logo-text {
    font-size: 16px;
  }
}
</style>